import { nextTick } from 'vue'
import { createI18n } from 'vue-i18n'
// import locale_zh_CN from '@/locales/zh_CN'
// import locale_en_US from '@/locales/en_US'

export const LOCALES = {
	"zh_CN": {
		"title": "中文",
	},
	"en_US": {
		"title": "English",
	}
};
export const SUPPORT_LOCALES = Object.keys(LOCALES);
export const DEFAULT_LOCALE = 'zh_CN'
export const DEFAULT_FALLBACK_LOCALE = 'zh_CN'

export function setupI18n(options = { locale: DEFAULT_LOCALE, fallbackLocale: DEFAULT_FALLBACK_LOCALE }) {
	const i18n = createI18n(options)
	setI18nLanguage(i18n, options.locale)
	return i18n
}

export function setI18nLanguage(i18n, locale) {
	if (i18n.mode === 'legacy') {
		i18n.global.locale = locale
	} else {
		i18n.global.locale.value = locale
	}
	/**
	 * NOTE:
	 * If you need to specify the language setting for headers, such as the `fetch` API, set it here.
	 * The following is an example for axios.
	 *
	 * axios.defaults.headers.common['Accept-Language'] = locale
	 */
	document.querySelector('html').setAttribute('lang', locale)
}

export function getI18nLanguage(i18n) {
	if (i18n.mode === 'legacy') {
		return i18n.global.locale
	} else {
		return i18n.global.locale.value
	}
}

export async function loadLocaleMessages(i18n, locale) {
	// load locale messages with dynamic import
	const messages = await import(
		/* webpackChunkName: "locale-[request]" */ `./locales/${locale}.json`
	)

	// set locale and locale message
	i18n.global.setLocaleMessage(locale, messages.default)

	return nextTick()
}



export const i18n = setupI18n({
	locale: DEFAULT_LOCALE, 
	fallbackLocale: DEFAULT_FALLBACK_LOCALE,
	messages: {
		// "zh_CN": locale_zh_CN,
		// "en_US": locale_en_US,
	}
});


export async function changeI18nLocale(locale) {
	// console.warn("changeI18nLocale: ", locale);

	// use locale if locale is not in SUPPORT_LOCALES
	if (!SUPPORT_LOCALES.includes(locale)) {
		locale = getI18nLanguage(i18n) || DEFAULT_LOCALE;
	}

	// load locale messages
	if (!i18n.global.availableLocales.includes(locale)) {
		await loadLocaleMessages(i18n, locale)
	}

	// set i18n language
	setI18nLanguage(i18n, locale)
}

export function translate(string) {
	return i18n.global.t(string);
}

export default i18n;
